------------------------------------------------------------------------------------------------------------------------------------------------
local function language_change_say(theNPC)
    theNPC.CHAT_TABLE = {}
    pcall(function()
        -- theNPC.npc_base_lib:Get_Language() == "ch"
        theNPC.CHAT_TABLE = TUNING.NPC_CHAT_TABLE[ theNPC.npc_base_lib:Get_Language() ] ["npc_event_livingtrees"] or {}
    end)
end
------------------------------------------------------------------------------------------------------------------------------------------------

local function freeze_players(theplayer)
    SpawnPrefab("lightning").Transform:SetPosition(theplayer.Transform:GetWorldPosition())

    if theplayer.components.freezable and not theplayer.components.freezable:IsFrozen() then
        local x,y,z = theplayer.Transform:GetWorldPosition()
        theplayer.components.freezable:Freeze(math.random(20, 30))
        local canthavetags = { "isdead","INLIMBO", "notarget", "noattack", "flight", "invisible", "playerghost" ,"chester","hutch","wall","structure"}
        local musthavetags = {"freezable"}
        local musthaveoneoftags = {"pig","rabbit","animal","smallcreature","epic","monster","insect"}
        local ents = TheSim:FindEntities(x, 0, z, 20, musthavetags, canthavetags, musthaveoneoftags)
        for k, v in pairs(ents) do
            if v.components.freezable and not v.components.freezable:IsFrozen() then
                if v:HasTag("player") then
                    v.components.freezable:Freeze(math.random(20, 30))
                else
                    v.components.freezable:Freeze(480)    
                end
            end
        end

    end
end

local function trees_around_player(theNPC,theplayer)
    local pt = Vector3(theplayer.Transform:GetWorldPosition())

    local points = theNPC.npc_base_lib:GetSurroundPoints({
        target = theplayer,
        range = 4,
        num = 10
    })

    for i, temp_pt in pairs(points) do
        theNPC:DoTaskInTime(i*0.5,function()
            local tree = SpawnPrefab("npc_item_livingtree")
            tree.Transform:SetPosition(temp_pt.x,0,temp_pt.z)
            SpawnPrefab("lightning").Transform:SetPosition(temp_pt.x,0,temp_pt.z)

        end)        
    end

    for i = 1, 30, 1 do
        theplayer:DoTaskInTime( (i*0.3) + 6,function()
            local r_pt = theplayer.npc_base_lib:GetSpawnPoint(pt,  math.random(30)/10  ) or pt
            SpawnPrefab("flower_evil").Transform:SetPosition(r_pt.x,0,r_pt.z)
        end)
    end

    theplayer:DoTaskInTime(20,function()
        local item_pt = theplayer.npc_base_lib:GetSpawnPoint(pt,  math.random(20)/10  ) or pt
        SpawnPrefab("axe").Transform:SetPosition(item_pt.x,20,item_pt.z)
        item_pt = theplayer.npc_base_lib:GetSpawnPoint(pt,  math.random(20)/10  ) or pt
        SpawnPrefab("shovel").Transform:SetPosition(item_pt.x,20,item_pt.z)
    end)
    
end
-------------------------------------------------------------------------------------------------------------------------------------------------


local function Time_Out_Leave(inst)
    local theNPC = inst.entity:GetParent()
    local time = theNPC.npc_base_lib:Get_Time_Out()
    if time then
        inst:DoTaskInTime(time,function()
            inst:Remove()
            theNPC:AddDebuff("npc_event_leave","npc_event_leave")
            theNPC.npc_base_lib:Say(theNPC.CHAT_TABLE.time_out)
        end)
    end
end

local function NPC_TASKS_INIT(inst)
    local theNPC = inst.entity:GetParent()
    language_change_say(theNPC)
    Time_Out_Leave(inst)
    
    theNPC.npc_base_lib:Equip_Random_Hat()
    theNPC.npc_base_lib:Equip_Random_Cloth()
    -- theNPC.npc_base_lib:Equip_Random_Weapon()
    theNPC.npc_base_lib:Equip(SpawnPrefab("diviningrod"))
    theNPC:AddTag("INLIMBO")
    theNPC:AddTag("notarget")
    theNPC:AddTag("noattack")
    theNPC:AddTag("invisible")
    theNPC:AddTag("Unable_To_Refuse")
    theNPC.npc_event = inst.prefab
end

local function NPC_TASKS(inst)
    local theNPC = inst.entity:GetParent()
    if TheWorld.state.isnight  or TheWorld:HasTag("cave") then
        theNPC.npc_base_lib:Try_2_Set_Light(true)
    else
        theNPC.npc_base_lib:Try_2_Set_Light(false)
    end
    local theplayer = theNPC.__link_player
    if theplayer == nil or theplayer:IsValid() == false then
        -- theNPC:RemoveDebuff(inst.prefab)
        inst:Remove()
        theNPC:AddDebuff("npc_event_leave","npc_event_leave")
        print("Warning : theNPC.__link_player == nil")
        return
    end

    if theNPC.event_step == nil then

        if theNPC.npc_base_lib:Close_2_Target_In_Range({range = 9}) == true then
            theNPC.event_step = 1
        end
        
    elseif theNPC.event_step == 1 then

        theNPC.npc_base_lib:Action_Gita()
        theNPC.event_step = theNPC.event_step + 1
        theNPC:DoTaskInTime(1.2,function()
            freeze_players(theplayer)
        end)
    elseif theNPC.event_step == 2 then
        -- freeze_players(theplayer)
        theNPC.event_step = theNPC.event_step + 1
    elseif theNPC.event_step == 3 then
       if theNPC.npc_everything_data:Add("task_time_wait_00",1)%4 == 0 then
            theNPC.event_step = theNPC.event_step + 1
        end        
    elseif theNPC.event_step == 4 then
        theNPC.npc_base_lib:Action_Gita()
        theNPC.event_step = theNPC.event_step + 1       
        theNPC:DoTaskInTime(0.7,function()
            -- freeze_players(theplayer)
            trees_around_player(theNPC,theplayer)
        end)
    elseif theNPC.event_step == 5 then
        -- trees_around_player(theNPC,theplayer)
        theNPC.event_step = theNPC.event_step + 1        
    elseif theNPC.event_step == 6 then
        if theNPC.npc_everything_data:Add("task_time_wait_01",1)%18 == 0 then
            theNPC.event_step = theNPC.event_step + 1
        end
    elseif theNPC.event_step == 7 then
        -- theNPC.event_step = theNPC.event_step + 1
        -- theNPC:RemoveDebuff(inst.prefab)
        inst:Remove()
        -- theNPC.npc_base_lib:Say("Bye ~ ")
        theNPC.npc_base_lib:Say(theNPC.CHAT_TABLE.hahaha)

        theNPC:AddDebuff("npc_event_leave","npc_event_leave")
    end
end
--------------------------------------------------------------------------------------------------------------------------------------------------

local function OnAttached(inst,target) -- when the debuff on or player is newSpawn(or through the cave)
    inst.entity:SetParent(target.entity)
    inst.Network:SetClassifiedTarget(target)
    local NPC = inst.entity:GetParent()
    local flag ,error_code= pcall(function(inst,target)
        if TheWorld.ismastersim then

            NPC_TASKS_INIT(inst)


        end
    end,inst,target)
    if flag == false  then
        print("Error : OnAttached(inst,target) ",inst.prefab)
        print(error_code)
        NPC:Remove()
    end
end

local function OnDetached(inst) -- When eliminating from the outside
    local player = inst.entity:GetParent()   
    -- print(" FROM OUSIDE REMOVE ")
    
    -- inst:Remove()
end

local function ExtendDebuff(inst)
    -- inst.countdown = 3 + (inst._level:value() < CONTROL_LEVEL and EXTEND_TICKS or math.floor(TUNING.STALKER_MINDCONTROL_DURATION / FRAMES + .5))
end



local function OnUpdate(inst,ismastersim)
    local NPC = inst.entity:GetParent()
    local flag,error_code = pcall(function(inst,ismastersim)
        -- local NPC = inst.entity:GetParent()

        NPC_TASKS(inst)


    end,inst,ismastersim)
    if flag == false then
        print("Error : OnUpdate(inst,ismastersim) ,step:",NPC.event_step ,inst.prefab)
        print(error_code)
        NPC:Remove()
    end
end

local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddNetwork()

    inst:AddTag("CLASSIFIED")


    -- inst:DoPeriodicTask(1, OnUpdate, nil, TheWorld.ismastersim)  -- in one seconds
    inst:DoPeriodicTask( 0.5, OnUpdate, nil, TheWorld.ismastersim)  -- in 0.5 seconds

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end

    inst:AddComponent("debuff")
    inst.components.debuff:SetAttachedFn(OnAttached)
    inst.components.debuff.keepondespawn = false -- 是否保持debuff 到下次登陆
    -- inst.components.debuff:SetDetachedFn(inst.Remove)
    inst.components.debuff:SetDetachedFn(OnDetached)
    -- inst.components.debuff:SetExtendedFn(ExtendDebuff)
    -- ExtendDebuff(inst)


    return inst
end

return Prefab("npc_event_livingtrees", fn)
